<template>
  <div ref="videoRef" class="video-view"></div>
</template>

<script setup lang="ts">
import 'xgplayer/dist/index.min.css';

import { nextTick, ref, watch } from 'vue';
import Player, { Events, IPlayerOptions } from 'xgplayer';

const props = defineProps({
  url: String,
});

const emits = defineEmits(['play', 'pause', 'load', 'error']);

const player = ref<Player>({} as Player);
const videoRef = ref<HTMLDivElement>();

const videoOptions: IPlayerOptions = {
  el: null,
  url: '',
  width: '100%',
  height: '100%',
  lang: 'zh-cn',
  volume: 0,
  autoplay: true,
  fitVideoSize: 'fixed',
  controls: false,
  videoFillMode: 'fill',
};

watch(
  () => props.url,
  async (url) => {
    await nextTick();
    videoOptions.url = url;
    videoOptions.el = videoRef.value;
    init();
  },
  { immediate: true },
);

const setVideoEvent = () => {
  player.value.on('play', () => {
    emits('play');
  });

  player.value.on('pause', () => {
    emits('pause');
  });

  player.value.on(Events.ERROR, () => {
    emits('error');
  });
};

// 初始化player
const init = () => {
  player.value = new Player({ ...videoOptions });
  setVideoEvent();
  emits('load');
};

const destroy = () => {
  if (!player.value) return;
  player.value.destroy();
  player.value = null;
};

const playNext = (url: string) => {
  player.value.playNext({ url });
};

defineExpose({ player, init, playNext, destroy });
</script>

<style lang="less" scoped>
.video-view {
  border-radius: 10px;
}
</style>
